package com.martin.lib_base.utils

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.martin.lib_base.interfaces.IRelease

/**
 * @desc：释放工具类
 */
object ReleaseUtil {

    // 可取消的集合
    private val releaseMap = HashMap<Any, ArrayList<IRelease>>()

    /**
     * 添加可取消的
     */
    fun add(key: Any, cancelable: IRelease) {
        if (!releaseMap.containsKey(key)) {
            releaseMap[key] = ArrayList()
        }
        releaseMap[key]?.add(cancelable)
    }

    /**
     * 取消
     */
    fun release(key: Any) {
        releaseMap[key]?.forEach {
            it.release()
        }
        releaseMap.remove(key)
    }

    /**
     * 取消全部
     */
    fun releaseAll() {
        releaseMap.forEach {
            it.value.forEach { cancelable ->
                cancelable.release()
            }
        }
        releaseMap.clear()
    }

}

/**
 * 添加可释放内容
 */
fun Any.addRelease(release: () -> Unit) {
    ReleaseUtil.add(this, object : IRelease {
        override fun release() {
            release()
        }
    })
}

/**
 * 添加可释放内容
 */
fun <T> T.addReleaseForKey(key: Any, release: (T) -> Unit): T {
    val that = this
    ReleaseUtil.add(key, object : IRelease {
        override fun release() {
            release(that)
        }
    })
    return this
}

/**
 * 根据生命周期释放
 */
fun <T : IRelease> T.releaseForLifecycle(owner: LifecycleOwner): T {
    val that = this
    owner.lifecycle
        .addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                owner.lifecycle.removeObserver(this)
                // 释放资源
                (that as IRelease).release()
                ReleaseUtil.release(that)
            }
        })

    return that
}
